<template>
  <div>
    <!-- default-expanded-keys="expandedKey" -->
    <el-tree
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      node-key="catId"
      default-expand-all
      show-checkbox
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0 && node.data.catId >= 9"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>

          <el-button type="text" size="mini" @click="() => edit(node, data)">
            修改
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      title: "",
      dialogType: "",
      category: {
        name: "",
        parentId: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null
      },
      dialogVisible: false,
      menus: [],
      expandedKey: [0],
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  methods: {
    // 提交方法
    submitData() {
      if (this.dialogType == "append") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    // 发送修改请求
    editCategory() {
      var { catId, name } = this.category;
      var data = { catId: catId, name: name };
      console.log("修改的数据:", data);
      this.$http({
        url: this.$http.adornUrl("/menu/category/update"),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单修改成功",
          type: "success"
        });
        this.dialogVisible = false;
        this.getMenus();
        this.expandedKey = [this.category.parentId];
        this.dialogVisible = false;
      });
    },
    // 修改
    edit(node, data) {
      this.title = "修改 分类 标签";
      this.dialogType = "edit";
      this.dialogVisible = true;
      // 发送请求获取 当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/menu/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        // console.log("获得的分类数据", data)
        this.category.name = data.category.name;
        this.category.catId = data.category.catId;
      });
      //   this.category.name = data.name;
      //   this.category.catId = data.catId;
    },
    // 添加表单书数据
    addCategory() {
      // console.log("提交的数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/menu/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单保存成功",
          type: "success"
        });
        this.dialogVisible = false;
        this.getMenus();
      });
    },
    handleNodeClick(data) {
      console.log(data);
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/menu/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        console.log("返回所有的分类列表",data.data);
        this.menus = data.data;
      });
    },
    // 添加
    append(data) {
      this.title = "添加 分类 标签";
      this.dialogType = "append";
      this.category.name = "";
      console.log("append", data);
      this.dialogVisible = true;
      this.category.parentId = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },

    //删除
    remove(node, data) {
      console.log("remove", node, data);
      var ids = [data.catId];
      this.$confirm(`是否删除当前 分类 标签 【${data.name}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/menu/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ node, data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500
              });
              this.getMenus();
              this.expandedKey = [this.category.parentId];
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  created() {
    this.getMenus();
  }
};
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
